package com.yiqi.zhiyuan.feature.home.view;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.amap.api.col.n3.ho;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.luck.picture.lib.entity.EventEntity;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.entity.bo.Result;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.DateUtil;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.common.widget.transition.CardPagerAdapter;
import com.yiqi.zhiyuan.common.widget.transition.ShadowTransformer;
import com.yiqi.zhiyuan.entity.vo.CarVO;
import com.yiqi.zhiyuan.entity.vo.HomeVO;
import com.yiqi.zhiyuan.entity.vo.OrderVO;
import com.yiqi.zhiyuan.feature.home.contract.HomeContract;
import com.yiqi.zhiyuan.feature.home.dependencies.home.DaggerHomeComponent;
import com.yiqi.zhiyuan.feature.home.dependencies.home.HomePresenterModule;
import com.yiqi.zhiyuan.feature.home.view.adapter.GrabFailDialog;
import com.yiqi.zhiyuan.feature.home.view.adapter.GrabOrderDialog;
import com.yiqi.zhiyuan.feature.home.view.adapter.ImmediatelyDialog;
import com.yiqi.zhiyuan.feature.login.view.LoginActivity;
import com.yiqi.zhiyuan.feature.msg.view.MessageActivity;
import com.yiqi.zhiyuan.feature.order.view.OrderInfoActivity;
import com.yiqi.zhiyuan.feature.order.view.OrderTripingActivity;
import com.yiqi.zhiyuan.feature.order.view.adapter.CancleOrderDialog;
import com.yiqi.zhiyuan.feature.order.view.adapter.CommonDialog;
import com.yiqi.zhiyuan.framework.DataServer;
import com.yiqi.zhiyuan.framework.ZYConstants;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import static com.suozhang.framework.component.websocket.WSHost.WSURL;
import static com.yiqi.zhiyuan.framework.ZYConstants.ORDER_JIXU;
import static com.yiqi.zhiyuan.framework.ZYConstants.ORDER_SHOUCHE;


public class HomeFragment extends BaseFragment implements CommonDialog.MyClickListenerInterface, HomeContract.View, OnRefreshListener, ImmediatelyDialog.MyClickListenerInterface {

    CommonDialog mCommonDialog;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.tv_home_score)
    TextView mTvHomeScore;
    @BindView(R.id.tv_home_order_count)
    TextView mTvHomeOrderCount;
    @BindView(R.id.tv_home_order_time)
    TextView mTvHomeOrderTime;
    @BindView(R.id.tv_home_car_info)
    TextView mTvHomeCarInfo;
    @BindView(R.id.tv_home_drive_like)
    TextView mTvHomeDriveLike;
    @BindView(R.id.btn_home_listen_start)
    TextView mBtnHomeListenStart;
    @BindView(R.id.vp_car)
    ViewPager mViewPager;
    @BindView(R.id.btn_home_order)
    TextView mBtnHomeOrder;
    @BindView(R.id.btn_home_listen_stop)
    TextView mBtnHomeListenStop;
    private static final int COMPLETED = 0;
    @BindView(R.id.rl_home_car_info)
    RelativeLayout mRlHomeCarInfo;
    @BindView(R.id.tv_show_dirver_stauts)
    TextView mTvShowDirverStauts;
    @BindView(R.id.tv_home_msg_count)
    TextView mTvHomeMsgCount;


    private WebSocket mSocket = null;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    String mTitle;
    private OkHttpClient mOkHttpClient = null;

    private int mListenType = -1;

    private CardPagerAdapter mCardAdapter;
    private ShadowTransformer mCardShadowTransformer;

    private OrderVO mDialogOrderVO = null;

    @Inject
    HomeContract.Presenter mPresenter;

    public static HomeFragment getInstance(String title) {
        HomeFragment sf = new HomeFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initInjector() {
        DaggerHomeComponent.builder().homePresenterModule(new HomePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        mPresenter.selectDriverHomeInfo();
    }

    @Override
    protected void initData() {
        initLocation();
    }

    @Override
    protected void initEvent() {
        mSmartRefreshLayout.setOnRefreshListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
    }


    @OnClick(R.id.btn_home_listen_start)
    public void onViewListenStartClicked() {
        if (mHomeVO == null && mHomeVO.getDriver() == null) return;
        if (mHomeVO.getDriver().getIsPass() != null&&mHomeVO.getCarDriver()!=null&&mHomeVO.getCarDriver().getIsPass()!=null) {
            if (mHomeVO.getDriver().getIsPass() == 2&&mHomeVO.getCarDriver().getIsPass()==2) {
                start();
            } else {
                showMsg("您还未审核，审核之后才能听单");
            }
        } else {
            showMsg("请先认证司机");
        }

    }


    @OnClick(R.id.rl_home_car_info)
    public void onViewCarInfoClicked() {
        mPresenter.selectCarList();
    }


    //    选择车型完成操作
    @Override
    public void doConfirm(CarVO carVO, int listenType) {
        mCommonDialog.dismiss();
        if (carVO != null) {
            mPresenter.orderQuickSetup(Integer.valueOf(carVO.getId()), listenType);
        }
    }

    @Override
    public void showHomeInfoSuccess(HomeVO homeVo) {
        mSmartRefreshLayout.finishRefresh();
        setHomeData(homeVo);
    }

    HomeVO mHomeVO;

    /**
     * 填充首页数据
     */
    private void setHomeData(HomeVO homeVo) {
        mHomeVO = homeVo;
        mTvHomeScore.setText(homeVo.getIntegral());
        mTvHomeOrderCount.setText(homeVo.getTodayOrdersNum());
        mTvHomeOrderTime.setText(homeVo.getTodayOnlineTime());
        mTvShowDirverStauts.setText(homeVo.getIsListen() == 1 ? "工作中" : "休息中");
        mListenType = homeVo.getListenPreferences();
        mTvHomeMsgCount.setVisibility(homeVo.getMessNum() > 0 ? View.VISIBLE : View.GONE);
        mTvHomeMsgCount.setText(homeVo.getMessNum() + "");
        if (homeVo.getCarDriver() != null) {
            mTvHomeCarInfo.setText(String.format("%s\t\t%s", homeVo.getCarDriver().getCarName(), homeVo.getCarDriver().getCarModelNo()));
            mTvHomeDriveLike.setText(String.format("%s%s", TextUtils.isEmpty(homeVo.getCarDriver().getLaber()) ? "无标签" : homeVo.getCarDriver().getLaber(), "\t\t" + DataServer.getListenType().get(homeVo.getListenPreferences())));
        } else {
            mTvHomeCarInfo.setText("");
            mTvHomeDriveLike.setText("");
        }
        //判断是否停单状态 0没听，1听单状态
        if (homeVo.getIsListen() == 0) {
            mBtnHomeListenStart.setVisibility(View.VISIBLE);
            mBtnHomeListenStop.setVisibility(View.GONE);
            mViewPager.setVisibility(View.GONE);
            mBtnHomeOrder.setVisibility(View.GONE);
        } else if (homeVo.getIsListen() == 1) {
            mPresenter.selectMissedOrderList(mAMapLocation!=null?mAMapLocation.getLongitude():0.00,mAMapLocation!=null?mAMapLocation.getLatitude():0.00);
            mBtnHomeListenStart.setVisibility(View.GONE);
            mBtnHomeListenStop.setVisibility(View.VISIBLE);
            if (mSocket == null) {
                start();
            }
        }
    }

    @Override
    public void showHomeInfoError(String errorMsg) {
        mSmartRefreshLayout.finishRefresh();
        showMsg(errorMsg);
    }

    @Override
    public void showOrderQuickSetupSuccess() {
        showMsg("快捷接单设置成功");
        mPresenter.selectDriverHomeInfo();
    }

    @Override
    public void showOrderQuickSetupError(String errorMsg) {
        showMsg("快捷接单设置失败" + errorMsg);
    }

    @Override
    public void showCarListSuccess(List<CarVO> homeVo) {
        mCommonDialog = new CommonDialog(getActivity(), homeVo);
        mCommonDialog.setCarListen(mListenType);
        mCommonDialog.setListener(this);
        mCommonDialog.show();
    }

    @Override
    public void showSelectCarListEmpty() {
        showMsg("暂无汽车信息");
    }

    @Override
    public void showSelectCarListError(String errorMsg) {
        showMsg(errorMsg);
    }


    ImmediatelyDialog immediatelyDialog = null;


    @Override
    public void showOrderSuccess(OrderVO orderVO) {
        mPresenter.selectDriverHomeInfo();
        mDialogOrderVO = null;
        if (immediatelyDialog != null) {
            immediatelyDialog.dismiss();
            immediatelyDialog = null;
        }

        if (orderVO.getUseCarType() == 1) {//接机单
            Intent intent = new Intent(getActivity(), OrderTripingActivity.class);
            intent.putExtra("order_info", orderVO);
            startActivity(intent);
        } else if (orderVO.getUseCarType() == 0) {//用车
            if (orderVO.getOrderType() == 0) {//现在
                immediatelyDialog = new ImmediatelyDialog(getActivity(), orderVO,mAMapLocation);
                immediatelyDialog.setListener(this);
                immediatelyDialog.show();
            } else if (orderVO.getOrderType() == 1) {//预约
                Intent intent = new Intent(getActivity(), OrderTripingActivity.class);
                intent.putExtra("order_info", orderVO);
                startActivity(intent);

            } else if (orderVO.getOrderType() == 2) {//代叫
                if (orderVO.getOrderFlag() == 0) {//现在出发
                    immediatelyDialog = new ImmediatelyDialog(getActivity(), orderVO,mAMapLocation);
                    immediatelyDialog.setListener(this);
                    immediatelyDialog.show();
                } else if (orderVO.getOrderFlag() == 1) {//预约时间
                    Intent intent = new Intent(getActivity(), OrderTripingActivity.class);
                    intent.putExtra("order_info", orderVO);
                    startActivity(intent);
                }
            }
        } else if (orderVO.getUseCarType() == 2) {
            if (orderVO.getOrderType() == 0) {//现在出发
                immediatelyDialog = new ImmediatelyDialog(getActivity(), orderVO,mAMapLocation);
                immediatelyDialog.setListener(this);
                immediatelyDialog.show();
            } else if (orderVO.getOrderType() == 1) {//预约时间
                Intent intent = new Intent(getActivity(), OrderTripingActivity.class);
                intent.putExtra("order_info", orderVO);
                startActivity(intent);
            }else if (orderVO.getOrderType() == 2) {//代叫
                if (orderVO.getOrderFlag() == 0) {//现在出发
                    immediatelyDialog = new ImmediatelyDialog(getActivity(), orderVO,mAMapLocation);
                    immediatelyDialog.setListener(this);
                    immediatelyDialog.show();
                } else if (orderVO.getOrderFlag() == 1) {//预约时间
                    Intent intent = new Intent(getActivity(), OrderTripingActivity.class);
                    intent.putExtra("order_info", orderVO);
                    startActivity(intent);
                }
            }
        }


    }

    @Override
    public void showOrderError() {
        mPresenter.selectDriverHomeInfo();
        GrabFailDialog grabFailDialog = new GrabFailDialog(getContext());
        grabFailDialog.show();
    }

    @Override
    public void showOrderError(String errorMsg) {
        showMsg(errorMsg);
    }

    /**
     * 立即前往成功
     */
    @Override
    public void showArriveAtLocationSuccess(OrderVO orderVO) {
        Intent intent = new Intent(getActivity(), OrderInfoActivity.class);
        intent.putExtra("order_info", orderVO);
        getActivity().startActivity(intent);
    }

    @Override
    public void showMissedOrderListError(String errorMsg) {
        mViewPager.setVisibility(View.GONE);
        mBtnHomeOrder.setVisibility(View.GONE);
        showMsg(errorMsg);
    }

    @Override
    public void showMissedOrderListSuccess(List<OrderVO> homeVo) {
        mViewPager.setVisibility(View.VISIBLE);
        mBtnHomeOrder.setVisibility(View.VISIBLE);
        fillViewPager(homeVo);
    }

    @Override
    public void showMissedOrderListEmpty() {
        mViewPager.setVisibility(View.GONE);
        mBtnHomeOrder.setVisibility(View.GONE);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        mPresenter.selectDriverHomeInfo();
    }


    private void start() {
        if (AM.user().isLogin()) {
            mOkHttpClient = new OkHttpClient.Builder()
                    .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                    .build();

            try {
                Request request = new Request.Builder()
                        .header("driverNo", AM.user().getLoginResultCache().getDriverNo())
                        .url(WSURL).build();
                EchoWebSocketListener socketListener = new EchoWebSocketListener();
                if (!mOkHttpClient.dispatcher().executorService().isShutdown()) {
                    mOkHttpClient.newWebSocket(request, socketListener);
                    mOkHttpClient.dispatcher().executorService().shutdown();
                }
            } catch (Exception e) {
                Logger.e(e.getMessage());
            }

        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    /**
     * 结束听单
     */

    @OnClick(R.id.btn_home_listen_stop)
    public void onViewStopListenClicked() {
        closeWebSocket();
    }

    /**
     * 抢单
     */

    @OnClick(R.id.btn_home_order)
    public void onViewOrderClicked() {
        try {
            OrderVO OrderVO = mCardAdapter.getData().get(mViewPager.getCurrentItem());
            if (OrderVO != null) {
                mPresenter.order(OrderVO.getOrderNo(), OrderVO.getUseCarType());
            }
        } catch (Exception e) {
            showMsg(e.getMessage());
        }
    }

    /**
     * 立即用车
     **/
    @Override
    public void doConfirm(OrderVO orderVO) {
        if (orderVO != null) {
            mPresenter.arriveAtLocation(orderVO.getOrderNo(), orderVO.getUseCarType());
        }
    }

    @OnClick(R.id.iv_home_msg)
    public void onViewMessageClicked() {
        getActivity().startActivity(new Intent(getActivity(), MessageActivity.class));
    }


    private final class EchoWebSocketListener extends WebSocketListener {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            mSocket = webSocket;
            //连接成功后，发送登录信息
            if (!AM.user().isLogin()) return;
            Map<String, Object> map = new HashMap<>();
            map.put("driverId", AM.user().getLoginResultCache().getId());
            map.put("isCloss", 0);
            String message = JSON.toJSONString(map);
            mSocket.send(message);
            output("连接成功！");
            mPresenter.selectDriverHomeInfo();
            test();
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            output("receive bytes:" + bytes.hex());
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            output("receive text:" + text);
            Result<OrderVO> result = JSONObject.parseObject(text, new TypeReference<Result<OrderVO>>() {
            });
            if (result.getCode() == 0) {
                if (result != null && result.getData() != null) {
                    handler.sendMessage(handler.obtainMessage(COMPLETED, result.getData()));
                }
            } else {
                showMsg(result.getMsg());
            }
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            output("closed:" + reason);
            mPresenter.selectDriverHomeInfo();
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            output("closing:" + reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            output("failure:" + t.getMessage());
            start();
        }
    }

    private void sendHeart() {

        if (!AM.user().isLogin()) return;
        //连接成功后，发送心跳包
        Map<String, Object> mapStr = new HashMap<>();
        mapStr.put("driverId", AM.user().getLoginResultCache().getId());
        if (mAMapLocation != null) {
            mapStr.put("lat", mAMapLocation.getLatitude());
            mapStr.put("lng", mAMapLocation.getLongitude());
        }
        String messageStr = JSON.toJSONString(mapStr);
        if (mSocket != null) {
            mSocket.send(messageStr);
            Logger.d("首页定位心跳包---》" + messageStr);
        }
    }

    private void test() {
        mCompositeDisposable.clear();
        mCompositeDisposable.add(Observable.interval(0, 5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(getObserver(1)));
    }

    private DisposableObserver getObserver(final int id) {
        DisposableObserver disposableObserver = new DisposableObserver<Object>() {
            @Override
            public void onNext(Object o) {
                sendHeart();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {
                Logger.e(e.toString());
            }
        };

        return disposableObserver;
    }

    private void output(final String text) {
        Logger.e(text);
    }


    /**
     * 填充ViewPager
     */
    private void fillViewPager(final List<OrderVO> vos) {
        try {
            mCardAdapter = new CardPagerAdapter();
            for (int i = 0; i < vos.size(); i++) {
                mCardAdapter.addCardItem(vos.get(i));
            }
            mCardAdapter.notifyDataSetChanged();
            mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);
            mCardShadowTransformer.enableScaling(true);
            mViewPager.setAdapter(mCardAdapter);
            mViewPager.setPageTransformer(false, mCardShadowTransformer);
            mViewPager.setOffscreenPageLimit(3);
        } catch (Exception e) {
//            showMsg(e.getMessage());
        }

    }


    public synchronized void closeWebSocket() {
        if (mSocket != null) {
            if (!AM.user().isLogin()) return;
            //连接成功后，发送登录信息
            Map<String, Object> map = new HashMap<>();
            map.put("driverId", AM.user().getLoginResultCache().getId());
            map.put("isCloss", 1);
            String message = JSON.toJSONString(map);
            mSocket.send(message);
            mSocket.close(1000, "byebye");
            mSocket = null;
        } else {
            start();
        }
        if (mCompositeDisposable!=null){
            mCompositeDisposable.clear();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(EventEntity obj) {
        switch (obj.what) {
            case ORDER_SHOUCHE:
                closeWebSocket();
                break;
            case ORDER_JIXU:
                break;

        }
    }


    /**
     * 接收解析后传过来的数据
     */
    GrabOrderDialog grabOrderDialog = null;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            try {
                OrderVO model = (OrderVO) msg.obj;
                if (model == null) return true;
                if (grabOrderDialog != null && grabOrderDialog.isShowing()) {
                    grabOrderDialog.dismiss();
                    grabOrderDialog = null;
                }

                if (model.getOrderStatus() == 0) {
                    if (mDialogOrderVO != null && mDialogOrderVO.getOrderNo().equals(model.getOrderNo())) {
                        if (grabOrderDialog != null && grabOrderDialog.isShowing()) {
                            grabOrderDialog.dismiss();
                            grabOrderDialog = null;
                        }
                        newOrderTip(model);
                    } else {
                        if (immediatelyDialog != null && immediatelyDialog.isShowing()) {
                            immediatelyDialog.dismiss();
                            immediatelyDialog = null;
                        }

                        RxBus.getDefault().post(new EventEntity(ZYConstants.ORDER_CANCLE, 0));
                        CancleOrderDialog cancleOrderDialog = new CancleOrderDialog(getActivity(), model, true);
                        cancleOrderDialog.show();
                        cancleOrderDialog.setListener(new CancleOrderDialog.MyClickListenerInterface() {
                            @Override
                            public void doConfirm() {
                                cancleOrderDialog.dismiss();
                            }
                        });
                    }

                } else {
                    newOrderTip(model);
                }


            } catch (Exception e) {
                showMsg(e.getMessage());
            }

            return false;
        }
    });

    /**
     * 新单提醒
     */
    private void newOrderTip(OrderVO model) {
        playerNewTaskTips();
        mDialogOrderVO = model;
        grabOrderDialog = new GrabOrderDialog(getActivity(), model, mAMapLocation);
        grabOrderDialog.show();
        grabOrderDialog.setListener(new GrabOrderDialog.MyClickListenerInterface() {
            @Override
            public void doConfirm(OrderVO orderVO) {
                mPresenter.order(orderVO.getOrderNo(), orderVO.getUseCarType());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWebSocket();
        RxBus.getDefault().unregister(this);
        // 如果退出程序，就清除后台任务
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }

    private static Vibrator vibrator;
    private static MediaPlayer player;

    /**
     * 新任务提示
     */
    private static void playerNewTaskTips() {
        try {
            //震动
            if (vibrator == null) {
                vibrator = (Vibrator) AM.app().getSystemService(Service.VIBRATOR_SERVICE);
            }
            vibrator.cancel();
            vibrator.vibrate(new long[]{80, 300, 80, 300, 80, 300}, -1);
            //音频播放
            if (player == null) {
                player = MediaPlayer.create(AM.app(), R.raw.new_order);
            }
            if (!player.isPlaying()) {
                player.start();
            }
        } catch (Throwable e) {
        }
    }

    private AMapLocationClient mLocationClient;
    private AMapLocation mAMapLocation;

    //    AmapRouteActivity
    private void initLocation() {
        mLocationClient = new AMapLocationClient(getActivity());
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        option.setInterval(2000);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
//                Logger.d("首页定位开启-----onLocationChanged---->");
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        mAMapLocation = amapLocation;
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    showMsg("location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }

        });
        mLocationClient.startLocation();
    }

}
